from django.shortcuts import render
from rest_framework.response import Response
# Create your views here.
from rest_framework.views import APIView
from . import models
from .serializer import *
from django.db.models import F
#新闻
class NewsView(APIView):
    def post(self,request):
        title=request.POST.get("title")
        new_filter=models.News.objects.filter(title=title)
        if new_filter:
            return Response({"code":1001,"msg":"数据存在"})
        obj=NewsViewSerializers(data=request.data)
        if obj.is_valid():
            flay=obj.save()
            if flay:
                return Response({"code":1000,"msg":"成功"})
            return Response({"code":1002,"msg":"失败"})
        print(obj.errors)
        return Response({"code":1003,"msg":"参数错误"})
    def get(self,request):
        obj=models.News.objects.all()
        new_obj=NewsViewSerializers(obj,many=True)
        return Response({"code":1000,"data":new_obj.data})


class Login(APIView):
    def post(self,request):
        name=request.POST.get('username')
        word=request.POST.get('password')
        user_obj=models.User.objects.filter(username=name).first()
        if user_obj:
            if user_obj.password==word:
                return Response({'msg': '登录成功', 'code': 1000,'user_id':user_obj.id})
            else:
                return Response({'msg': '用户名或密码错误', 'code': 1001})
        else:
            return Response({'msg': '登录失败', 'code': 1002})


class AddComment(APIView):
    def post(self,request):
        comment_serializer = CommentModelSerializer(data=request.data)
        if comment_serializer.is_valid():
            comment_serializer.save()
        user=request.POST.get('user')
        comment=models.Comment.objects.filter(user=user).first()
        if comment.comment_count < 3:
            news = models.News.objects.get(pk=request.data.get('news'))
            news.total_comment += float(1)
            news.save()
            comment.comment_count += float(1)
            num=comment.comment_count
            comment.save()
            return Response({'msg': '您还有{}次评论机会'.format(3-num), 'code': 1000})
        else:
            return Response({'msg': '评论超出限制，请明天再来评论', 'code': 1001})


class ShowNews(APIView):
    def get(self,request,uid):
        news=models.News.objects.get(pk=uid)
        news.total_views+=float(1)
        news.save()
        news_serializer=NewsModelSerializer(news)
        return Response(news_serializer.data)


class ShowComment(APIView):
    def get(self,request,uid):
        comment=models.Comment.objects.filter(news=uid)
        comment_serializer=CommentModelSerializer(comment,many=True)
        return Response(comment_serializer.data)


class ShowInfo(APIView):
    def get(self,request):
        nwes=models.News.objects.filter(total_views__gt=F('total_comment'))
        print(nwes)
        return Response(nwes)


